<template>
  <div class="login-page" v-if="isNeedBind">
    <nav-bar></nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        name="mobile"
        v-model="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
      ></van-field>
      <van-field
        name="code"
        v-model="code"
        :rules="codeRules"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}秒后重试` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { loginByQQ, loginBind } from '@/api/user'
import { User } from '@/types/user'
import { mobileRules, codeRules } from '@/utils/rules'
import { useSendMobileCode } from '@/hook'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
const router = useRouter()
const { login } = useStore()
const mobile = ref('')
const code = ref('')
// 登录成功之后获取的openId
const openId = ref('')
// 是否已经绑定了手机
const isNeedBind = ref(false)
const { form, time, send } = useSendMobileCode(mobile, 'bindMobile')
const loginSuccess = (user: User) => {
  if (user.bindingFlag === false) return

  // 保存到仓库中
  login.setLoginInfo(user)
  // 跳转到对应的页面
  router.replace(login.redirectUrl || '/my')
  // 提示
  Toast.success('登录成功~')
  login.setRedirectUrl('')
}
onMounted(() => {
  if (window.QC.Login.check()) {
    // 登录了
    window.QC.Login.getMe(id => {
      openId.value = id

      loginByQQ(id)
        .then(res => {
          isNeedBind.value = !res.data.bindingFlag
          // 第三方登录成功
          loginSuccess(res.data)
        })
        .catch(() => {
          isNeedBind.value = true
        })
    })
  }
})
// 绑定手机号
const bind = async () => {
  const res = await loginBind({
    openId: openId.value,
    mobile: mobile.value,
    code: code.value
  })

  if (res.code === 10000) {
    loginSuccess(res.data)
  } else {
    Toast.fail(res.message)
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
